package io.jpress.service.provider;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import io.jboot.aop.annotation.Bean;
import io.jboot.db.model.Column;
import io.jpress.commons.service.JPressServiceBase;
import io.jpress.core.template.Template;
import io.jpress.model.Permission;
import io.jpress.model.PermissionGroup;
import io.jpress.service.PermissionGroupService;
import io.jpress.service.PermissionService;

import java.util.List;

@Bean
public class PermissionGroupServiceProvider extends JPressServiceBase<PermissionGroup> implements PermissionGroupService {

    @Inject
    private PermissionService permissionService;

    @Override
    public void sync(List<PermissionGroup> permissionGroups) {
        DAO.deleteAll();
        Db.batchSave(permissionGroups,permissionGroups.size());
    }

    @Override
    public void syncGroupAndPemissions(PermissionGroup group) {
        if (group == null){
            DAO.deleteById(Template.TEMPLATE_LOGIC_PERMISSION_GROUP_ID);

            List<Permission> permissions = permissionService.findListByGroupId(Template.TEMPLATE_LOGIC_PERMISSION_GROUP_ID);
            if (permissions != null){
                for (Permission permission : permissions) {
                    permissionService.delete(permission);
                }
            }
        }else {

            PermissionGroup byId = DAO.findById(group.getId());
            if (byId == null) {
                group.save();
            } else {
                group.update();
            }

            List<Permission> permissions = group.getPermissions();
            if (permissions != null && permissions.size() > 0) {
                for (Permission permission : permissions) {
                    Permission existsPermission = permissionService.findById(permission.getId());
                    if (existsPermission == null) {
                        permissionService.save(permission);
                    } else {
                        permissionService.update(permission);
                    }
                }
            }
        }

    }

    @Override
    public List<PermissionGroup> findListByType(Integer type) {
        return DAO.findListByColumn(Column.create("type",type));
    }
}